package com.jtw.sys.listener.mvcInterceptor;

import com.jtw.sys.service.log.SysAccessServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.Date;


/**
 * @Descript: 日志记录
 * @author chenjian
 * @date 2018-208-22 14:28
 */
@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

//    @Autowired
//    private SessionDAO sessionDAO;
    @Autowired
    private SysAccessServiceImpl sysAccessService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("=======preHandle1=======");
//        System.out.println("最大的活跃时间"+request.getSession().getMaxInactiveInterval());
//        System.out.println("最后访问时间"+request.getSession().getLastAccessedTime());
//        System.out.println(request.getSession().getId());
//        Cookie [] cookies = request.getCookies();
//        System.out.println("cookie中的信息共有"+cookies.length+"条");
//        for(Cookie c:cookies){
//            System.out.println(
//                    "isHttpOnly==>"+c.isHttpOnly()+
//                    ",getComment==>"+c.getComment()+
//                    ",getName==>"+c.getName()+
//                    ",getValue==>"+c.getValue()+
//                    ",getDomain==>"+c.getDomain()+
//                    ",getPath==>"+c.getPath()+
//                    ",getSecure==>"+c.getSecure()+
//                    ",getVersion==>"+c.getVersion());
//        }


//        Collection<Session> activeSessions = sessionDAO.getActiveSessions();
//        for (Session sessions : activeSessions) {
//            log.info("---sessionid----"+session.getId()+"----timeout---"+sessions.getTimeout()+"----lasttime---"+sessions.getLastAccessTime());
//            long time1 = sessions.getLastAccessTime().getTime();
//            log.info("----LastAccessTime----"+time1);
//            long time2 = new Date().getTime();
//            log.info("----currentTime----"+time2);
//            long timeout = sessions.getTimeout();
//            log.info("----差值----"+(time2 -time1));
//            if ((time2 - time1) > timeout) {
//                log.info("----true----");
//                activeSessions.remove(session);
//            }
//        }


//        System.out.println(request.getSession().getId());
//        System.out.println(request.getRequestedSessionId());
//        System.out.println(request.getSession().getAttribute(Constant.KEY_CSRF_TOKEN));
//        System.out.println(request.getSession().getAttribute(Constant.KEY_CSRF_TOKEN));
//        System.out.println(request.getSession().getAttribute(Constant.KEY_USER_USER_NAME));
//        log.information("当前请求的getRequestURI为"+request.getRequestURI());
//        log.information("当前请求的"+Constant.KEY_CSRF_TOKEN+"为"+request.getHeader(Constant.KEY_CSRF_TOKEN));
//        log.information("当前请求的getMethod为"+request.getMethod());
//        log.information("当前请求的getQueryString为"+request.getQueryString());
//        log.information("当前请求的getParameterMap为"+request.getParameterMap());
//        log.information("当前请求的getContentType为"+request.getContentType());
//        log.information("当前请求的sessionid为"+request.getRequestedSessionId());
//        log.information("当前请求的PathInfo为"+request.getPathInfo());
//        log.information("当前请求的PathTranslated为"+request.getPathTranslated());
//        log.information("当前请求的ContextPath为"+request.getContextPath());
//        log.information("当前请求的getAuthType为"+request.getAuthType());
//        log.information("当前请求的getRemoteUser为"+request.getRemoteUser());
//        log.information("当前请求的getServletPath为"+request.getServletPath());
//        log.information("当前请求的getCharacterEncoding为"+request.getCharacterEncoding());
//        log.information("当前请求的getLocalAddr为"+request.getLocalAddr());
//        log.information("当前请求的getLocalName为"+request.getLocalName());
//        log.information("当前请求的getProtocol为"+request.getProtocol());
//        log.information("当前请求的getRemoteHost为"+request.getRemoteHost());
//        log.information("当前请求的getRemoteAddr为"+request.getRemoteAddr());
//        log.information("当前请求的getScheme为"+request.getScheme());
//        log.information("当前请求的getServerName为"+request.getServerName());
//        log.information("当前请求的getCookies为"+request.getCookies());
//        log.information("当前请求的getLocale为"+request.getLocale());
//        log.information("当前请求的getLocalPort为"+request.getLocalPort());
//        log.information("当前请求的getParameterNames为"+request.getParameterNames());
//        log.information("当前请求的getRemotePort为"+request.getRemotePort());
//        log.information("当前请求的getServerPort为"+request.getServerPort());
//        log.information("当前请求的getHeader为"+request.getHeader("User-Agent"));
//
//        TSysAccessLog sysAccessLog = new TSysAccessLog();
//
//        UserAgent userAgent = DeviceUtil.getByRequest(request);
//        Browser browser = DeviceUtil.getBrowserByUserAgent(userAgent);
//        OperatingSystem operatingSystem = DeviceUtil.getOperatingSystemByUserAgent(userAgent);
//
//        if (userAgent!=null){
//            log.information("浏览器版本:"+userAgent.getBrowserVersion());
//            sysAccessLog.setBrowserVersion(userAgent.getBrowserVersion().toString());
//        }else {
//            sysAccessLog.setBrowserVersion("未检测到浏览器版本");
//        }
//
//        if(browser!=null){
//            log.information("浏览器名:"+browser.getName());
//            log.information("浏览器类型:"+browser.getBrowserType());
//            log.information("浏览器家族:"+browser.getGroup());
//            log.information("浏览器生产厂商:"+browser.getManufacturer());
//            log.information("浏览器使用的渲染引擎:"+browser.getRenderingEngine());
//            log.information("操作系统名:"+operatingSystem.getName());
//            sysAccessLog.setBrowserType(browser.getBrowserType().toString());
//            sysAccessLog.setBrowserName(browser.getGroup().toString());
//        }else{
//            sysAccessLog.setBrowserType("未检测到浏览器类型");
//            sysAccessLog.setBrowserName("未检测到浏览器名称");
//        }
//
//        if(operatingSystem!=null){
//            log.information("访问设备类型:"+operatingSystem.getDeviceType());
//            log.information("操作系统家族:"+operatingSystem.getGroup());
//            log.information("操作系统生产厂商:"+operatingSystem.getManufacturer());
//            sysAccessLog.setOs(operatingSystem.getName());
//        }else{
//            sysAccessLog.setOs("未检测到设备类型");
//        }
//
//        try {
//            Subject subject = SecurityUtils.getSubject();
//            if(subject.isAuthenticated()){
//                Long id = (Long) subject.getSession().getAttribute(Constant.USER_PRIMARY_KEY);
//                sysAccessLog.setUserId(id);
//            }
//        }catch (UnavailableSecurityManagerException e){
//            log.information("出错啦！！！");
//            log.error(e.getMessage());
//        }
//
//        sysAccessLog.setUrl(request.getRequestURI());
//        sysAccessLog.setAddress(IpUtil.getIpFromAttribution(request.getLocalAddr()));
//        sysAccessLog.setHttpMethod(request.getMethod());
//        sysAccessLog.setIp(request.getLocalAddr());
//        sysAccessLog.setRenderEngine(browser.getRenderingEngine().toString());
//        Long start = Calendar.getInstance().getTimeInMillis();
//        sysAccessLog.setPort(String.valueOf(request.getLocalPort()));
//
//        if(request.getMethod().equals(HttpMethod.GET.toString())){
//            sysAccessLog.setParams(request.getQueryString());
//        }else if(request.getMethod().equals(HttpMethod.POST.toString())){
//            String t = new ObjectMapper().writeValueAsString(request.getParameterMap());
//            sysAccessLog.setParams(t);
//        }
//        sysAccessService.save(sysAccessLog);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("=====post1======");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("======afterCompletion1=======");
    }
}
